<template>
  <el-dialog title="附件管理" :visible.sync="show" width="555px">
    <avue-form ref="form" :option="attachOption" v-model="attachForm" :upload-before="uploadBefore" :show-file-list="false" multiple :upload-after="uploadAfter"></avue-form>
  </el-dialog>
</template>

<script>
const XLSX = require('xlsx');
export default {
  data() {
    return {
      current:'',
      show: false,
      attachForm: [],
      fileText: [],
      attachOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            prop: 'attachFile',
            type: 'upload',
            loadText: '文件上传中，请稍等',
            span: 24,
            drag: true,
            propsHttp: {
              url: 'url',
              name: 'name',
              res: 'data'
            },
            action: '/api/blade-resource/oss/endpoint/put-file-attach'
          }
        ]
      }
    };
  },
  methods: {
    open(index) {
      this.current=index;
      this.fileText=[];
      this.show = true;
    },
    uploadBefore(file, done, loading, column) {
      console.log(file);
      const types = file.name.split('.');
      const type = types[types.length - 1];
      const fileType = ['xlsx', 'xls', 'XLSX', 'XLS'].some(item => item == type);
      if (!fileType) {
        loading();
        this.$message.error('格式错误！请重新选择');
        return;
      }
      this.load(file);
      loading();
    },
    load(files) {
      console.log(files)
      let result = [];
      let reader = new FileReader();
      reader.readAsBinaryString(files);
      reader.onload = e => {
        const data = e.target.result;
        const wb = XLSX.read(data, {
          type: 'binary'
        });
        wb.SheetNames.forEach(sheetName => {
          result.push(XLSX.utils.sheet_to_json(wb.Sheets[sheetName], { header: 1, defval: '' }));
        });
        let obj = result[0];
        console.log(obj)
        for (let i = 0; i < obj.length; i++) {
          let arr = {};
          if (i >= 1) {
            arr.sort=i;
            arr.cailiaoNumber = obj[i][1];
            arr.cailiaoName = obj[i][2];
            arr.cailiaoSku = obj[i][3];
            arr.category = obj[i][4];
            arr.cailiaoQty = obj[i][5];
            arr.cailiaoUnit = obj[i][6];
            arr.supplierName = obj[i][7];
            this.fileText.push(arr);
          }
          if(i>=obj.length-1){
            console.log(222)
            this.show=false;
            this.$emit('onConfirm',{cailiaoList:this.fileText,index:this.current})
          }
        }
      }
    }
  }
};
</script>

<style></style>
